package com.javayz.fileuploadanddownload.controller;

import com.javayz.fileuploadanddownload.entity.Files;
import com.javayz.fileuploadanddownload.entity.all;
import com.javayz.fileuploadanddownload.service.FileService;
import com.javayz.fileuploadanddownload.util.ZipUtils;
import net.sf.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author by:
 * @ClassName: FileController
 * @Description: TODO 文件上传
 * @Date:
 */

@RestController
@RequestMapping("/api")
public class FileController {
    @Autowired
    private FileService fileService;
    @Value("${file.save-path}")
    private String savePath;
    /**
     *@描述  获取文件夹名
     *@参数 [newFileName]
     *@返回值 java.util.List<java.lang.String>
     *@创建人 ZLQ
     *@创建时间 2022/11/4 11:04
     *@修改人和其它信息
     */
    @GetMapping("fileName")
    public List<String> findAll(@RequestParam("tableName") String tableName){
        return fileService.fileAll(tableName);
    }
    @RequestMapping(value = "/insertData", method = RequestMethod.POST)
    public Map<String,String> insertData(@RequestBody List<all> allList) {

        Map<String,String> map = new HashMap<>();
        for (all a:allList) {
            if("外协框架协议".equals(a.getTable_name())){
                fileService.deleteWxkjxy(a.getSource_pk());
                fileService.insertwxkjxy(a);
            }
            if("外协合同".equals(a.getTable_name())){
                fileService.deleteWxht(a.getSource_pk());
                fileService.insertWxht(a);
            }
            if("工程基本信息".equals(a.getTable_name())){
                fileService.deleteGcjbxx(a.getSource_pk());
                fileService.insertGcjbxx(a);
            }
            if("销售合同".equals(a.getTable_name())){
                fileService.deleteXsht(a.getSource_pk());
                fileService.insertXsht(a);
            }
            if("施工框架协议".equals(a.getTable_name())){
                fileService.deleteSgkjxy(a.getSource_pk());
                fileService.insertSgkjxy(a);
            }
            if("计划成本编制".equals(a.getTable_name())){
                fileService.deleteJhcbbz(a.getSource_pk());
                fileService.insertJhcbbz(a);
            }
            if("工程决算管理".equals(a.getTable_name())){
                fileService.deleteGcjsgl(a.getSource_pk());
                fileService.insertGcjsgl(a);
            }
            if("决算成本编制".equals(a.getTable_name())){
                fileService.deleteJscbbz(a.getSource_pk());
                fileService.insertJscbbz(a);
            }
            if("外协计划".equals(a.getTable_name())){
                fileService.deleteWxjh(a.getSource_pk());
                fileService.insertWxjh(a);
            }
            if("外协结算".equals(a.getTable_name())){
                fileService.deleteWxjs(a.getSource_pk());
                fileService.insertWxjs(a);
            }
            if("收入发票登记".equals(a.getTable_name())){
                fileService.deleteSrfpdj(a.getSource_pk());
                fileService.insertSrfpdj(a);
            }
            if("外协费".equals(a.getTable_name())){
                fileService.deleteWxf(a.getSource_pk());
                fileService.insertWxf(a);
            }
        }
        map.put("code","200");
        map.put("message","数据同步成功");
        return map;
    }


    /**
     *@描述： 文件单个下载
     *@参数： [sourcePk, response]
     *@返回值： void
     *@创建人： ZLQ
     *@创建时间： 2022/11/8 9:13
     *@修改人和其它信息：
     */
    @RequestMapping(value = "/downloadFile", method = RequestMethod.GET)
    public  void  downloadFile(@RequestParam("id") String[] id,
                               HttpServletResponse response) {

        //数据库中查找文件信息
        List<Files> files = fileService.getFileById(id);
        //遍历获取到的每条数据
        for (Files forFiles : files){
            if (forFiles.getNickname() == null || forFiles.getNickname().length() == 0) {

                ZipUtils.downFile(response, forFiles.getFilePath() + "/" + forFiles.getFileName());
            }else{
                ZipUtils.FixFileName(forFiles.getFilePath()+"/"+forFiles.getNickname()+forFiles.getFileSuffix(),forFiles.getFilePath()+"/"+forFiles.getFileName());
                ZipUtils.downFile(response, forFiles.getFilePath() + "/" + forFiles.getFileName());
                ZipUtils.FixFileName(forFiles.getFilePath()+"/"+forFiles.getFileName(),forFiles.getFilePath()+"/"+forFiles.getNickname()+forFiles.getFileSuffix());
            }
        }
    }

    /**
     *@描述： 文件批量下载
     *@参数： [sourcePk, response]
     *@返回值： void
     *@创建人： ZLQ
     *@创建时间： 2022/11/8 9:13
     *@修改人和其它信息：
     */
    @RequestMapping(value = "/download", method = RequestMethod.GET)
    public void downloadFiles(@RequestParam("id") String[] id,
                              HttpServletResponse response){

        Date d=new Date();
        d.setTime(System.currentTimeMillis());
        //生成时间戳
        SimpleDateFormat format=new SimpleDateFormat("yyyyMMddHHmmss");
        //准备压缩文件夹名称
        String dateFile = savePath+"/"+format.format(d);
        File newFile = new File(dateFile);
        //创建文件夹
        if (!newFile.exists()) {
            //如果不存在创建文件夹
            newFile.mkdirs();
        }
        //数据库中查找文件信息
        List<Files> files = fileService.getFileById(id);
        //遍历获取到的每条数据
        for (Files forFiles : files) {
            if (forFiles.getNickname() == null || forFiles.getNickname().length() == 0) {
                String tableName = fileService.selectTableName(forFiles.getSourcePk());
                all allEngineeringNo = fileService.selectEngineeringNo(tableName, forFiles.getSourcePk());
                //forFiles.getFilePath()获取数据库中的文件路径
                String str = forFiles.getFilePath();
                //对文件路径进行拆分
                str = str.substring(str.indexOf("/"), str.lastIndexOf("/"));
                //拆分指定原文件夹名称,str为数据库中的指定文件夹名称
                str = str.substring(str.lastIndexOf("/"));
                String dateUrl = null;
                //如果工程编码为空
                if (allEngineeringNo.getEngineering_no() == null) {
                    //下载路径为"日期文件夹+指定报名+编码"
                    dateUrl = dateFile + "/" + str + "/" + forFiles.getSourcePk();
                } else {
                    //不为空下载路径为"日期文件夹+指定报名+工程编码"
                    dateUrl = dateFile + "/" + str + "/" + allEngineeringNo.getEngineering_no();
                }
                try {
                    fileService.inputStream(forFiles, dateUrl);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else {
                ZipUtils.FixFileName(forFiles.getFilePath() + "/" + forFiles.getNickname() + forFiles.getFileSuffix(), forFiles.getFilePath() + "/" + forFiles.getFileName());
                String tableName = fileService.selectTableName(forFiles.getSourcePk());
                all allEngineeringNo = fileService.selectEngineeringNo(tableName, forFiles.getSourcePk());
                //forFiles.getFilePath()获取数据库中的文件路径
                String str = forFiles.getFilePath();
                //对文件路径进行拆分
                str = str.substring(str.indexOf("/"), str.lastIndexOf("/"));
                //拆分指定原文件夹名称,str为数据库中的指定文件夹名称
                str = str.substring(str.lastIndexOf("/"));
                String dateUrl = null;
                //如果工程编码为空
                if (allEngineeringNo.getEngineering_no() == null) {
                    //下载路径为"日期文件夹+指定报名+编码"
                    dateUrl = dateFile + "/" + str + "/" + forFiles.getSourcePk();
                } else {
                    //不为空下载路径为"日期文件夹+指定报名+工程编码"
                    dateUrl = dateFile + "/" + str + "/" + allEngineeringNo.getEngineering_no();
                }
                try {
                    fileService.inputStream(forFiles, dateUrl);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                ZipUtils.FixFileName(forFiles.getFilePath() + "/" + forFiles.getFileName(), forFiles.getFilePath() + "/" + forFiles.getNickname() + forFiles.getFileSuffix());
            }
        }
        //dateFile 路径加压缩文件名称，newFile 创建的文件夹路径, response 设置消息头
        fileService.deleteFile(dateFile, newFile, response);
    }

    /**
     *@描述： 文件上传
     *@参数： [files]
     *@返回值： java.util.Map<java.lang.String,java.lang.Object>
     *@创建人： ZLQ
     *@创建时间： 2022/11/4 11:06
     *@修改人和其它信息：
     */
    @RequestMapping("/uploadFile")
    @ResponseBody
    public Map<String, Object> uploadFiles(@RequestParam(value = "file") MultipartFile[] files ,
                                           @RequestParam(value = "newFileName") String newFileName,
                                           @RequestParam(value = "sourcePk" ) String[] sourcePk,
                                           @RequestParam(value = "tableName" ) String[] tableName,
                                           @RequestParam(value = "tableFileName") String tableFileName
                                           ) {

        Map<String, Object> result = new HashMap<>();
        if (files == null || files.length == 0) {
            result.put("msg", "上传失败,请先选择文件");
            return result;
        }

        try {
            List<String> oks = new ArrayList<>();
            for (MultipartFile file : files) {
                fileService.upLoadFiles(file, newFileName, sourcePk, tableName,tableFileName);
                String ok = "ok";
                oks.add(ok);
            }
            result.put("ok", oks);
        } catch (Exception e) {
        }
        return result;
    }

    /**
     *@描述：对模态框中数据进行筛选
     *@参数： [resp, sourcePk, tableName, filePathName]
     *@返回值： void
     *@创建人： ZLQ
     *@创建时间： 2022/11/25 16:40
     *@修改人和其它信息：
     */
    @ResponseBody
    @RequestMapping(value = "/selectAll",produces = {"application/text;charset=UTF-8"})
    public void selectAll(HttpServletResponse resp,
                          @RequestParam(value = "sourcePk") String[] sourcePk,
                          @RequestParam(value = "tableName") String tableName,
                          @RequestParam(value = "filePathName") String filePathName,
                          @RequestParam(value = "tableFileName") String tableFileName) {

        try {
            List<String> files = new ArrayList<>();
            for (String sourcePks : sourcePk){
                List<String> file = null;
                String urlFile = savePath+"/"+tableFileName+"/"+filePathName+"/"+sourcePks;
                String str = urlFile;
                str = str.substring(str.indexOf("/"),str.lastIndexOf("/"));
                //拆分指定原文件夹名称
                str = str.substring(str.lastIndexOf("/"));
                str = str.replace("/","");
                if (!str.equals("")){
                    file = fileService.selectAll(sourcePks, tableName, urlFile);
                }else {
                    file = fileService.selectAll(sourcePks, tableName, null);
                }
                files.addAll(file);
            }
            JSONArray data = JSONArray.fromObject(files);
            resp.setCharacterEncoding("utf-8");
            PrintWriter respWritter = resp.getWriter();
            respWritter.append(data.toString());

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    /**
     *@描述：删除方法
     *@参数： [id]
     *@返回值： java.util.Map<java.lang.String,java.lang.String>
     *@创建人： ZLQ
     *@创建时间： 2023/2/7 9:11
     *@修改人和其它信息：
     */
    @RequestMapping(value = "/deleteVbillstatuIds")
    public Map<String , String> deleteVbillstatuIds(@RequestParam String id ){
        Map<String , String> map = new HashMap<>();
        Files files = fileService.selectVbillstatus(id);
        all alls = fileService.selectVbillstatuIds(files.getTableName(),files.getSourcePk());
        if ("自由状态".equals(alls.getVbillstatus())){
            String url = files.getFilePath()+"/"+files.getNickname()+files.getFileSuffix();
            ZipUtils.deleteFile(url);
            fileService.deleteVbillstatus(id);
            map.put("code","200");
        }else {
            map.put("message","当前数据不是:"+"自由状态");
            return map;
        }
        return map;
    }

    @RequestMapping(value = "/queryLists")
    public void queryList( @RequestParam(value = "source_pk") String[] sourcePk,
                           HttpServletResponse resp) {

        try {
            /*list集合中存放的是好多student对象*/
            List<String> wxkjxy = fileService.queryLists(sourcePk);
            /*将list集合装换成json对象*/
            JSONArray data = JSONArray.fromObject(wxkjxy);
            //接下来发送数据
            /*设置编码，防止出现乱码问题*/
            resp.setCharacterEncoding("utf-8");
            /*得到输出流*/
            PrintWriter respWritter = resp.getWriter();
            /*将JSON格式的对象toString()后发送*/
            respWritter.append(data.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @RequestMapping(value = "/queryTableGcjbxx")
    public void queryTableGcjbxx( @RequestParam(value = "source_pk") String[] sourcePk,
                                  HttpServletResponse resp) {

        try {
            List<String> gcjbxx = fileService.queryTableGcjbxx(sourcePk);
            JSONArray data = JSONArray.fromObject(gcjbxx);
            resp.setCharacterEncoding("utf-8");
            PrintWriter respWritter = resp.getWriter();
            respWritter.append(data.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @RequestMapping(value = "/queryTableGcjsgl")
    public void queryTableGcjsgl( @RequestParam(value = "source_pk") String[] sourcePk,
                                  HttpServletResponse resp) {

        try {
            List<String> list = fileService.queryTableGcjsgl(sourcePk);
            JSONArray data = JSONArray.fromObject(list);
            resp.setCharacterEncoding("utf-8");
            PrintWriter respWritter = resp.getWriter();
            respWritter.append(data.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @RequestMapping(value = "/queryTableJhcbbz")
    public void queryTableJhcbbz( @RequestParam(value = "source_pk") String[] sourcePk,
                                  HttpServletResponse resp) {

        try {
            List<String> list = fileService.queryTableJhcbbz(sourcePk);
            JSONArray data = JSONArray.fromObject(list);
            resp.setCharacterEncoding("utf-8");
            PrintWriter respWritter = resp.getWriter();
            respWritter.append(data.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @RequestMapping(value = "/queryTableJscbbz")
    public void queryTableJscbbz( @RequestParam(value = "source_pk") String[] sourcePk,
                                  HttpServletResponse resp) {

        try {
            List<String> list = fileService.queryTableJscbbz(sourcePk);
            JSONArray data = JSONArray.fromObject(list);
            resp.setCharacterEncoding("utf-8");
            PrintWriter respWritter = resp.getWriter();
            respWritter.append(data.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @RequestMapping(value = "/queryTableSgkjxy")
    public void queryTableSgkjxy( @RequestParam(value = "source_pk") String[] sourcePk,
                                  HttpServletResponse resp) {

        try {
            List<String> list = fileService.queryTableSgkjxy(sourcePk);
            JSONArray data = JSONArray.fromObject(list);
            resp.setCharacterEncoding("utf-8");
            PrintWriter respWritter = resp.getWriter();
            respWritter.append(data.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @RequestMapping(value = "/queryTableSrfpdj")
    public void queryTableSrfpdj( @RequestParam(value = "source_pk") String[] sourcePk,
                                  HttpServletResponse resp) {

        try {
            List<String> list = fileService.queryTableSrfpdj(sourcePk);
            JSONArray data = JSONArray.fromObject(list);
            resp.setCharacterEncoding("utf-8");
            PrintWriter respWritter = resp.getWriter();
            respWritter.append(data.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @RequestMapping(value = "/queryTableWxf")
    public void queryTableWxf( @RequestParam(value = "source_pk") String[]sourcePk,
                               HttpServletResponse resp) {

        try {
            List<String> list = fileService.queryTableWxf(sourcePk);
            JSONArray data = JSONArray.fromObject(list);
            resp.setCharacterEncoding("utf-8");
            PrintWriter respWritter = resp.getWriter();
            respWritter.append(data.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @RequestMapping(value = "/queryTableWxht")
    public void queryTableWxht( @RequestParam(value = "source_pk") String[] sourcePk,
                                HttpServletResponse resp) {

        try {
            List<String> list = fileService.queryTableWxht(sourcePk);
            JSONArray data = JSONArray.fromObject(list);
            resp.setCharacterEncoding("utf-8");
            PrintWriter respWritter = resp.getWriter();
            respWritter.append(data.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @RequestMapping(value = "/queryTableWxjh")
    public void queryTableWxjh( @RequestParam(value = "source_pk") String[] sourcePk,
                                HttpServletResponse resp) {

        try {
            List<String> list = fileService.queryTableWxjh(sourcePk);
            JSONArray data = JSONArray.fromObject(list);
            resp.setCharacterEncoding("utf-8");
            PrintWriter respWritter = resp.getWriter();
            respWritter.append(data.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @RequestMapping(value = "/queryTableWxjs")
    public void queryTableWxjs( @RequestParam(value = "source_pk") String[] sourcePk,
                                HttpServletResponse resp) {

        try {
            List<String> list = fileService.queryTableWxjs(sourcePk);
            JSONArray data = JSONArray.fromObject(list);
            resp.setCharacterEncoding("utf-8");
            PrintWriter respWritter = resp.getWriter();
            respWritter.append(data.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @RequestMapping(value = "/queryTableWxkjxy")
    public void queryTableWxkjxy( @RequestParam(value = "source_pk") String[] sourcePk,
                                  HttpServletResponse resp) {

        try {
            List<String> list = fileService.queryTableWxkjxy(sourcePk);
            JSONArray data = JSONArray.fromObject(list);
            resp.setCharacterEncoding("utf-8");
            PrintWriter respWritter = resp.getWriter();
            respWritter.append(data.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @RequestMapping(value = "/queryTableXsht")
    public void queryTableXsht(@RequestParam(value ="source_pk") String[] sourcePk,
                               HttpServletResponse resp) {

        try {
            List<String> list = fileService.queryTableXsht(sourcePk);
            JSONArray data = JSONArray.fromObject(list);
            resp.setCharacterEncoding("utf-8");
            PrintWriter respWritter = resp.getWriter();
            respWritter.append(data.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @RequestMapping(value = "/selectAllTable")
    public Map<String,Object> selectAllTable() {

        try {
            List<String> tableName = new ArrayList<>();
            tableName.add("gcjbxx");
            tableName.add("gcjsgl");
            tableName.add("jhcbbz");
            tableName.add("jscbbz");
            tableName.add("sgkjxy");
            tableName.add("srfpdj");
            tableName.add("wxf");
            tableName.add("wxht");
            tableName.add("wxjh");
            tableName.add("wxjs");
            tableName.add("wxkjxy");
            tableName.add("xsht");
            Map<String,Object> map= new HashMap<>();
            for(int i = 11 ; i >= 0 ; i--){
                String value = fileService.selectAllTable(tableName.get(i));
                String s = tableName.get(i);
                map.put(s,value);
            }
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

}
